package com.cg.controller;

import com.cg.config.RedisCache;
import com.cg.entity.LoginUser;
import com.cg.entity.ResponseResult;
import com.cg.entity.User;
import com.cg.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@RequiredArgsConstructor
public class LoginController {

    private final AuthenticationManager authenticationManager;

    private final RedisCache redisCache;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user) {
        //AuthenticationManager authenticate进行用户认证
        Authentication authenticate = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));

        //认证未通过提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登陆失败");
        }
        //通过即使用userid生成一个jwt并存入responseResult
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String jwtToken = JwtUtils.getJwtToken(loginUser.getId().toString());
        Map<String, String> map = new HashMap<>();
        map.put("token", jwtToken);
        //把完整的用户信息存入redis userid作为key
        redisCache.setCacheObject("login:" + loginUser.getId(), loginUser, 1, TimeUnit.DAYS);
        return new ResponseResult(200, map);
    }

    @GetMapping("/loginOut")
    public ResponseResult loginOut() {
        //获取SecurityContextHolder中的用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser user = (LoginUser) authentication.getPrincipal();
        //删除redis中的key
        redisCache.deleteObject("login:" + user.getId());
        return new ResponseResult(200);
    }

}
